/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.commit.web;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeeplus.modules.commit.entity.stundent;
import com.jeeplus.modules.sys.entity.StudentMoreduMain;
import com.jeeplus.modules.sys.entity.StudentMoreduViceAdd;
import com.jeeplus.modules.sys.mapper.StudentMoreduMainMapper;
import com.jeeplus.modules.sys.mapper.StudentMoreduViceAddMapper;
import com.jeeplus.modules.sys.service.StudentMoreduMainService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.commit.entity.StudentSubmit;
import com.jeeplus.modules.commit.service.StudentSubmitService;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 终审流程Controller
 * @author 姜盼
 * @version 2022-01-27
 */
@RestController
@RequestMapping(value = "/commit/studentSubmit")
public class StudentSubmitController extends BaseController {

	@Autowired
	private StudentSubmitService studentSubmitService;
	@Resource
	private StudentMoreduMainService studentMoreduMainService;
	@Autowired
	private StudentMoreduViceAddMapper studentMoreduViceAddMapper;
	@Autowired
	private StudentMoreduMainMapper studentMoreduMainMapper;
	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	@ModelAttribute
	public StudentSubmit get(@RequestParam(required=false) String id) {
		StudentSubmit entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = studentSubmitService.get(id);
		}
		if (entity == null){
			entity = new StudentSubmit();
		}
		return entity;
	}
	/**
	 * 手机端提交档案加分申请流程
	 */

	@GetMapping("addpoint")
	public AjaxJson addpoint(stundent stundent) {
		try {
			StudentMoreduMain Main = studentMoreduMainService.getid(stundent.getNum());  //根据学号获取主表
			StudentMoreduViceAdd studentMoreduViceAdd = new StudentMoreduViceAdd();
			studentMoreduViceAdd.preInsert(); //插入id
			studentMoreduViceAdd.setAdd(Main); //主表信息
			studentMoreduViceAdd.setAddReason(stundent.getReason()); //加分原因
			studentMoreduViceAdd.setAddPoint(stundent.getPoint()); //加分数
			studentMoreduViceAdd.setAddState("0");//审核状态
//			Date date=new Date();
//			long d = date.getTime()+(3600000*8);
			studentMoreduViceAdd.setAddTime(new Date()); //加分时间
			if ("".equals(stundent.getFileUrl()) || stundent.getFileUrl() == null){
				studentMoreduViceAdd.setAddEnclosure("");
			} else {
				String[] url =  stundent.getFileUrl().split("/nginx-1.23.2/html");
				studentMoreduViceAdd.setAddEnclosure(url[1]); //附件
			}
			studentMoreduViceAddMapper.insert(studentMoreduViceAdd);
		}catch (Exception e) {
			return AjaxJson.error("添加失败");
		}
		return AjaxJson.success("添加成功");
	}

	/**
	 * 德育加分一键同意审批接口
	 * ids 前端行级id用，分割
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:agree")
	@GetMapping("process")
	public AjaxJson process(String ids,String approverPeople) {
		// 同意之后，先将缓存全部清空，然后再将新数据保存到缓存中
		try {
			String [] arr = ids.split(",");
			logger.info("清空所有缓存");
			Set<String> keys = redisTemplate.keys("*");
			for (String key : keys) {
				redisTemplate.delete(key);
				logger.info(key);
			}
			for (String i: arr
			) {
				StudentMoreduViceAdd studentMoreduViceAdd = studentMoreduViceAddMapper.get(i);   //根据行级id获取整条加分数据
				StudentMoreduMain add = studentMoreduViceAdd.getAdd();  // 获取每条加分的主表id
				StudentMoreduMain studentMoreduMain = studentMoreduMainMapper.get(add.getId()); //获取主表数据
				Integer childrenPoint = Integer.parseInt(studentMoreduViceAdd.getAddPoint()); //每条加分项的加分数
				Integer mainPoint = studentMoreduMain.getCurrentMoraleduPoint();  //转型成integer相加
				studentMoreduMain.setCurrentMoraleduPoint(childrenPoint + mainPoint);
				studentMoreduMainMapper.update(studentMoreduMain); //把德育分存入主表中
				studentMoreduViceAdd.setAddState("1"); //把附表审核状态修改成已通过
				Date date=new Date();
				long d = date.getTime()+(3600000*8);
				studentMoreduViceAdd.setAuditTime(new Date(d));
				if (approverPeople != null) { // 加入审核人
					studentMoreduViceAdd.setApprover(approverPeople);
				}
				studentMoreduViceAddMapper.update(studentMoreduViceAdd); //把附表数据存入数据库
			}
		}catch (NullPointerException e)  {
			return AjaxJson.error("请选择审核数据");
			}
		return AjaxJson.success("审核成功");
	}
	/**
	 * 德育加分一键审批不同意接口
	 * ids 前端行级id用，分割
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:disagree")
	@GetMapping("disagerrprocess")
	public AjaxJson disagerrprocess(String ids ,String approverPeople) {
        try {
		String[] arr = ids.split(",");
		for (String i : arr
		) {
			StudentMoreduViceAdd studentMoreduViceAdd = studentMoreduViceAddMapper.get(i);   //根据行级id获取整条加分数据
			studentMoreduViceAdd.setAddState("2");  //修改状态值
			Date date=new Date();
			long d = date.getTime()+3600000;
			studentMoreduViceAdd.setAuditTime(new Date(d));
			if (approverPeople != null) { // 加入审核人
				studentMoreduViceAdd.setApprover(approverPeople);
			}
			studentMoreduViceAddMapper.update(studentMoreduViceAdd); //更新数据
		}
    }catch (NullPointerException e)  {
        return AjaxJson.error("请选择审核数据");
    }
		return AjaxJson.success("审核成功");
	}
	/**
	 * 终审流程列表数据
	 */
	@GetMapping("list")
	public AjaxJson list(StudentSubmit studentSubmit, HttpServletRequest request, HttpServletResponse response) {
		Page<StudentSubmit> page = studentSubmitService.findPage(new Page<StudentSubmit>(request, response), studentSubmit);
		return AjaxJson.success().put("page",page);
	}
	/**
	 * 流程查询下级接口
	 * pram 德育主表对象
	 */
	@GetMapping("gradelist")
	public AjaxJson gradelist(String  yuan) {
		if (yuan != null){
			List<String> gradelist = studentMoreduMainService.gradelist(yuan);
			return AjaxJson.success().put("gradelist",gradelist);
		}
		return AjaxJson.success();
	}

	/**
	 * 流程查询下级接口
	 * pram 德育主表对象
	 */
	@GetMapping("downlist")
	public AjaxJson downlist(StudentMoreduMain studentMoreduMain) {
		List<StudentMoreduMain> downlist = studentMoreduMainService.downlist(studentMoreduMain);
		return AjaxJson.success().put("downlist",downlist);
	}
	/**
	 * 根据Id获取终审流程数据
	 */
	@GetMapping("queryById")
	public AjaxJson queryById(StudentSubmit studentSubmit) {
		return AjaxJson.success().put("studentSubmit", studentSubmit);
	}

	/**
	 * 保存终审流程
	 */
	@PostMapping("save")
	public AjaxJson save(StudentSubmit studentSubmit, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(studentSubmit);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑保存
		studentSubmitService.save(studentSubmit);//保存
		return AjaxJson.success("保存终审流程成功").put("businessTable", "student_submit").put("businessId", studentSubmit.getId());
	}


	/**
	 * 批量删除终审流程
	 */
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			studentSubmitService.delete(new StudentSubmit(id));
		}
		return AjaxJson.success("删除终审流程成功");
	}


}